package com.softWang.file.util.impl;

import com.softWang.common.utils.WebUtils;
import com.softWang.file.constants.FilesConstant;
import com.softWang.file.mapper.FileManageMapper;
import com.softWang.file.po.FileManage;
import com.softWang.file.util.MimeTypeUtils;
import com.softWang.file.vo.fileManage.FileSaveResult;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.Objects;
import java.util.UUID;

import com.softWang.file.util.IFileSaveUtil;

import javax.annotation.Resource;

@Component("FileSaveUtilDiskImpl")
public class FileSaveUtilDiskImpl implements IFileSaveUtil {

    @Value("${file.savePath}")
    private  String savePath;

    @Value("${file.fileSaveType}")
    private  String fileSaveType;
    @Resource
    private FileManageMapper fileManageMapper;

    @Override
    public FileSaveResult saveFile(MultipartFile file, String subDir, String fileName) throws Exception{
        // 上传文件路径
        String fileDir = savePath;
        String fileSubPath = subDir + "/" + fileName;
        String absPath = getAbsoluteFile(fileDir, fileSubPath).getAbsolutePath();
        file.transferTo(Paths.get(absPath));
        FileSaveResult result = new FileSaveResult();
        result.setFileUrl(FilesConstant.RESOURCE_PREFIX + "/" + subDir + "/" + fileName);
        return result;
    }

    @Override
    public String getFileUrl(FileManage baseFile) throws Exception {
        String fileUrl = WebUtils.getDomain() + baseFile.getFileUrl();
        return fileUrl;
    }

    @Override
    public void deleteFile(FileManage baseFile) throws Exception {
        String filePath = savePath + "/" + baseFile.getFileDiskPath() + "/" +baseFile.getFileName();
        File file = new File(filePath);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists())
        {
            file.delete();
        }
    }


    private File getAbsoluteFile(String uploadDir, String fileName) throws IOException
    {
        File desc = new File(uploadDir + File.separator + fileName);
        if (!desc.exists())
        {
            if (!desc.getParentFile().exists())
            {
                desc.getParentFile().mkdirs();
            }
        }
        return desc;
    }

}
